package game.module.ddz.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRoom;
import game.module.ddz.logic.DdzDataManager;
import game.module.hall.logic.QipaiDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzForceDismisroom;
import lua.LuaMessageDdz.PushDdzForceDismissRoom;
import lua.LuaMessageDdz.S2CDdzForceDismisroom;
import lua.LuaMessageLogin.S2ErrorCode;

//@MsgCodeAnn(msgcode = 1C2SDismissRoom.id, accessLimit = 500)
@MsgCodeAnn(msgcode = C2SDdzForceDismisroom.id, accessLimit = 500)
public class DdzDismissRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzDismissRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		int playerId = hero.getId();
		logger.info("ddz dismiss room,playeyId={}", playerId);
		// 是否在房间中
		boolean isInRoom = DdzDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is room exist
		DdzRoom ddzRoom = DdzDataManager.getInstance().getDdzRoomByPlayerId(playerId);
		if (ddzRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is room master -2017年8月18日 取消房主校验
		/*if (ddzRoom.getPlayerList().get(0) != playerId) {
			S2ErrorCode respMsg = new S2ErrorCode(107);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}*/
		// push
		List<Integer> playerIdList = ddzRoom.getPlayerList();
//		1PushDismissRoom pushMsg = new PushDismissRoom();
		PushDdzForceDismissRoom pushMsg = new PushDdzForceDismissRoom();
		pushMsg.player_index = (byte) playerIdList.indexOf(playerId);
		for (Integer aPlayerId : playerIdList) {
//			if (aPlayerId == playerId) {
//				continue;
//			}
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
				logger.info("ddz dismiss room" );
			}
		}
		// do
		DdzDataManager.getInstance().removeRoom(ddzRoom.getUuid());
		QipaiDataManager.getInstance().removeRoomUuid(ddzRoom.getUuid());
		// send
//		1S2CDismissRoom respMsg = new S2CDismissRoom();
		S2CDdzForceDismisroom respMsg = new S2CDdzForceDismisroom();
		hero.writeAndFlush(respMsg.build(hero.alloc()));
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// null
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// null
	}

}
